package com.itlong.cloud.rabbitmq.consumer;

import com.itlong.cloud.POJO.PO.TimeTaskDeadMessageQueuePO;
import com.itlong.cloud.POJO.PO.TimeTaskParkingErrorOrderPO;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.service.ITimeTaskParkingErrorOrderService;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <desc>
 *     保存用户登录日志消息队列消费者
 * </desc>
 *
 * @createDate 2018/04/28
 */
@Component
public class ParkingErrorOrdersConsumer {

    private static final Logger LOG = LoggerFactory.getLogger(ParkingErrorOrdersConsumer.class);

    @Autowired
    private ITimeTaskParkingErrorOrderService iTimeTaskParkingErrorOrderService;


    /**
     * <desc>
     *     保存停车场错误指令
     * </desc>
     *
     * @param message 监听到的业务消息
     * @param channel 频道
     * @author Jiaqi.X
     * @createDate 2018/11/15
     */
    @RabbitListener(queues = RabbitMQConstant.RABBITMQ_PARKING_ERROR_ORDER_QUEUE)
    public void process(Message message, Channel channel) throws IOException {
        byte[] body = message.getBody();
        try {
            TimeTaskDeadMessageQueuePO timeTaskDeadMessageQueuePO = JsonUtil.toObject(new String(body),
                    TimeTaskDeadMessageQueuePO.class);
            String params = timeTaskDeadMessageQueuePO.getMessageContent();
            Map<String,Object> map = JsonUtil.toObject(params, HashMap.class);
            TimeTaskParkingErrorOrderPO po = JsonUtil.toObject(JsonUtil.toJSON(map.get("message")), TimeTaskParkingErrorOrderPO.class);
            po.setErrorId(LogicIdUtil.bussinessId());
            iTimeTaskParkingErrorOrderService.save(po);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
            LOG.error("【RabbitMQ_保存停车场错误指令】:消费异常",e);
        } finally {
            //手动确认消息消费成功。
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }
    }

}
